﻿using luck_roll.Properties;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace luck_roll.Config
{
    public class ConfigHelper
    {
        public static string currentPath;

        public static AppConfig currentAppConfig { get; }

        static ConfigHelper()
        {
            currentPath = Environment.CurrentDirectory;
            string configFilePath = Path.Combine(currentPath, "app.json");
            if (File.Exists(configFilePath))
            {
                string fileContent = String.Empty;
                using (StreamReader sr = new StreamReader(configFilePath, Encoding.UTF8))
                {
                    fileContent = sr.ReadToEnd();
                }
                if (!String.IsNullOrEmpty(fileContent))
                {
                    currentAppConfig = JsonConvert.DeserializeObject<AppConfig>(fileContent);
                }
            }
            else
            {
                currentAppConfig = new AppConfig();
            }

            if (string.IsNullOrEmpty(currentAppConfig.BackgroundImage))
            {
                String backgroundImagePath = Path.Combine(currentPath, "resources", "background_image.jpg");
                if(File.Exists(backgroundImagePath))
                {
                    currentAppConfig.BackgroundImage = backgroundImagePath;
                }            
            }
        }

        /// <summary>
        /// 保存配置信息
        /// </summary>
        /// <returns></returns>
        public static bool SaveConfig()
        {
            if (currentAppConfig == null)
            {
                return false;
            }

            string configFilePath = Path.Combine(currentPath, "app.json");

            String content = JsonConvert.SerializeObject(currentAppConfig);

            if (String.IsNullOrEmpty(content))
            {
                return false;
            }

            try
            {
              
                using (FileStream fs = new FileStream(configFilePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                    {
                        sw.Write(content);
                        sw.Flush();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            return true;
        }
    }
}
